//
//  OAuthViewController.swift
//  swft_weibo
//
//  Created by mac on 15/9/11.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class OAuthViewController: UIViewController {
    let appID="3057635862"
    let appScret="1bad38082ecd13412e2cf5d1761bae7a"
    let redirectURL="http://www.baidu.com"
    
    let baiduSTR="http://www.baidu.com"
    override func loadView() {
        view=webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
    }
//MARK: - 懒加载的方法
    lazy var webView :UIWebView={
        
        let smallWebView=UIWebView()
        //设置代理
        smallWebView.delegate=self
        //设置webview加载的url
        let smallRequest=NSURLRequest(URL: NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=3057635862&redirect_uri=http://www.baidu.com")!)
        smallWebView.loadRequest(smallRequest)
        
        return smallWebView
    
    }()
    
}
//MARK: - UIWebViewDelegate代理方法
extension OAuthViewController: UIWebViewDelegate{
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        print(request.URL?.absoluteString)
        
        let url=request.URL?.absoluteString
        
        let result = url!.hasPrefix(baiduSTR)
        //判断是不是返回的地址中有code码
        if result {
            let tk = url! as NSString
            let index=tk.rangeOfString("code=")
            let code=tk.substringFromIndex(index.location+index.length)
            print(code)
            //获得网络访问工具类
            let networkTool = NetworkTools.shareNetworkTools()
            
            let path = "oauth2/access_token"
            let params = ["client_id" : appID,"client_secret" : appScret,"grant_type":"authorization_code","code":code,"redirect_uri":redirectURL]
            //发送网络请求去获取对应的accesstoken信息
            networkTool.POST(path, parameters: params, success: { (dataTask, jsonObject) -> Void in
                
                
                let userAccount = UserAccount(dic: jsonObject as! [String : AnyObject])
                print(userAccount)
                //通过调用模型中的方法来发送一个获取用户基本信息的链接，然后通过返回一个闭包来保存当前的用户信息。
                userAccount.loadUserInformation{
                    (userAccount)->Void in
                    
                    UserAccount.saveUserAccount(userAccount)
                }
                
                print(UserAccount)
                
                //在这里发送通知跳转界面，跳转到用户欢迎界面中去
                NSNotificationCenter.defaultCenter().postNotificationName("convertRootCtroller", object: true)
                
                }, failure: { (dataTask, error) -> Void in
                print(error)
            })
            return false
        }
        return true
    }
    //
    func webViewDidStartLoad(webView: UIWebView) {
        
    }
    //
    func webViewDidFinishLoad(webView: UIWebView) {
        
        
    }
    

}